<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>被围绕的区域</title>
</head>
<body>
  <script>
    function fn(board) {
      let row = board.length;
      if (row === 0) return [];
      let col = board[0].length;
      // 边界O上下左右坐标
      let dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
      const dfs = (i, j) => {
        if (i >= 0 && i < row && j >= 0 && j < col && board[i][j] === 'O') {
          board[i][j] = '@';
          // 作用是查找边界O上下左右是否有O，有的话替换为@
          for (let dir of dirs) {
            dfs(i + dir[0], j + dir[1]);
          }
        }
      }
      for (let i = 0; i < row; i++) {
        if (i === 0 || i === row - 1) {
          // 处理上下边界
          for (let j = 0; j < col; j++) {
            if (board[i][j] === 'O') {
              dfs(i, j);
            }
          }
        } else {
          // 处理左右边界
          for (let j of [0, col - 1]) {
            if (board[i][j] === 'O') {
              dfs(i, j);
            }
          }
        }
      }
      // 将包围区里面的O替换为X
      for (let i = 0; i < row; i++) {
        for (let j = 0; j < col; j++) {
          if (board[i][j] === 'O') {
            board[i][j] = 'X'
            // 将边界@还原
          } else if (board[i][j] === '@') {
            board[i][j] = 'O'
          }
        }
      }
    }
    console.log(fn([['X']]))
  </script>
</body>
</html>